package com.unism.common.rest.filters;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import com.unism.util.MapTool;
public class ParamFilter implements ContainerRequestFilter {

	@Override
	public void filter(ContainerRequestContext requestContext) throws IOException {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
				UriInfo uriInfor=requestContext.getUriInfo();
				Iterator iterator=null;
				//post 请求体中的参数
				Map<String, Object> param=new HashMap<>();
			    InputStream inputStream = requestContext.getEntityStream();
			    String str=inputStreamToString(inputStream);
			    Boolean isOk=MapTool.isJSON(str);
			    if(null != str && !str.trim().equals("") && isOk){
			    	MapTool.parseJSON2Map(str,param);
			    }
			    
			    
			    //@queryParam
				 MultivaluedMap<String, String> queryParam= uriInfor.getQueryParameters();
			        iterator=queryParam.keySet().iterator();
			        while(iterator.hasNext()){
			        	String key=(String) iterator.next();
			        	List<String> value=queryParam.get(key);
			        	param.put(key,value);
			      }
			       //@pathParam 
			        MultivaluedMap<String, String> pathParam= uriInfor.getPathParameters();
			        iterator=pathParam.keySet().iterator();
			        while(iterator.hasNext()){
			        	String key=(String) iterator.next();
			        	List<String> value=pathParam.get(key);
			        	param.put(key,value);
			        }
			        
			      requestContext.setProperty("param",param); 
	}
	
	private String inputStreamToString(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }

}
